﻿using System;
using System.Collections.Generic;
using AnjLab.SyncIT.Core.Api;
using AnjLab.SyncIT.Core.Data.Outlook;
using Converter = AnjLab.SyncIT.Core.Data.GoogleCode.GoogleTimeStringConverter;
using System.Net;

namespace AnjLab.SyncIT.Core.Data.GoogleCode
{
    public class GoogleCodeIssueDao : ISourceTaskDao
    {
        private readonly GoogleCodeIssueParser _parser;
        private readonly Source _source;

        public GoogleCodeIssueDao(Source source)
        {
            _source = source;
            _parser = new GoogleCodeIssueParser(source);
        }

        public void Dispose()
        {
        }

        public string[] GetChangedTasks()
        {
            Library.Log.Info(string.Format("Searching all opened tasks for user \"{0}\"", _source.UserName));

            if (_source.UserName == null || _source.UserName.Equals(string.Empty))
            {
                throw new InvalidOperationException("Can't find user's issue list since UserName isn't specified");
            }

            IList<string> result = new List<string>();

            SearchIssues(result);

            return ((List<string>) result).ToArray();
        }

        public ISourceTask Get(string taskID)
        {
            try
            {
                return _parser.ParseIssue(taskID);
            }
            catch (WebException e)
            {
                if (((HttpWebResponse) e.Response).StatusCode == HttpStatusCode.NotFound)
                {
                    return null;
                }
                throw;
            }
        }

        public bool CanTrackTaskLifetime
        {
            get { return false; }
        }

        public void CheckConnection()
        {
            _parser.Ping();
        }

        private void SearchIssues(ICollection<string> result)
        {
            IList<Issue> issues = _parser.FindFirst();

            while (issues.Count > 0)
            {
                foreach (Issue issue in issues)
                {
                    if (result.Contains(issue.ID))
                    {
                        continue;
                    }

                    Library.Log.Debug("Issue added " + issue);
                    result.Add(issue.ID);
                }

                issues = _parser.FindNext();
            }
        }

        public bool SupportsBackSynchronization
        {
            get { return false; }
        }

        public void MergeTasks(ISourceTask task, IOutlookItem outlookTask)
        {
            throw new NotSupportedException();
        }
    }
}